
package com.ojoin.trade.common.web.controller;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ojoin.trade.common.utils.LogUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ojoin.trade.common.utils.Config;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;

@Controller
@RequestMapping("/system/activemq")
public class ActivemqMonitorController  extends SimpleBaseController {

	private static final String HealthStatus=",service=Health/CurrentStatus";
	private static final String Slave="/Slave";
	private static final String Uptime="/Uptime";
	private static final String TransportConnectors="/TransportConnectors";
	private static final String CurrentConnectionsCount="/CurrentConnectionsCount";
	private static final String QueueSubscribers="/QueueSubscribers";

	private static final String StartQueueSizeOfCatchDataTask=",destinationType=Queue,destinationName=catchDataTask/QueueSize";
	private static final String CCOfCatchDataTask=",destinationType=Queue,destinationName=catchDataTask/ConsumerCount";



	private static final Logger logger = LoggerFactory
			.getLogger(ActivemqMonitorController.class);

	
	@ResponseBody
	@RequestMapping(value = "status", method = RequestMethod.GET)
	public Result status() throws SchedulerException {
		Map<String,Object> ret =new HashMap();
		try{
			String hs=jolokiaAPI(HealthStatus);
			ret.put("HStatus", JSONUtils.parseObject(hs, Map.class).get("value"));
			
			String ut=jolokiaAPI(Uptime);
			ret.put("Uptime", JSONUtils.parseObject(ut, Map.class).get("value"));
			
			String tc=jolokiaAPI(TransportConnectors);
			ret.put("TConnectors", JSONUtils.parseObject(tc, Map.class).get("value"));
			
			String cc=jolokiaAPI(CurrentConnectionsCount);
			ret.put("CConnectionCount", JSONUtils.parseObject(cc, Map.class).get("value"));

			String startCatchTask=jolokiaAPI(StartQueueSizeOfCatchDataTask);
			ret.put("StartQueueSizeOfCatchDataTask", JSONUtils.parseObject(cc, Map.class).get("value"));

			String ccCatchTask=jolokiaAPI(CCOfCatchDataTask);
			ret.put("CCOfCatchDataTask", JSONUtils.parseObject(cc, Map.class).get("value"));

			
			String qp=jolokiaAPI(QueueSubscribers);
			
			List<Map> list=(List) JSONUtils.parseObject(qp, Map.class).get("value");
			StringBuffer sb=new StringBuffer();

			for(Map entry:list){
				sb
				.append(entry.get("objectName"))
				.append(",");
			}
			ret.put("QueueProducers",sb.toString());
			
		}catch(Exception e){
			return new Result(Status.ERROR, e.getMessage());
		}
		return new Result(Status.OK, ret);
	}
	
	public static String jolokiaAPI(String attr) throws ClientProtocolException, IOException, URISyntaxException {
	    String username = "admin";
	    String password = "admin";
	    
	    URI mqUrl = new URI(Config.getProperty(Config.defConfig,"activeMQ.apiURL"));
	    HttpHost targetHost = new HttpHost(mqUrl.getHost(), mqUrl.getPort(), "http");

	    CredentialsProvider credsProvider = new BasicCredentialsProvider();
	    credsProvider.setCredentials(AuthScope.ANY, 
	      new UsernamePasswordCredentials(username, password));

	    AuthCache authCache = new BasicAuthCache();
	    authCache.put(targetHost, new BasicScheme());

	    // Add AuthCache to the execution context
	    final HttpClientContext context = HttpClientContext.create();
	    context.setCredentialsProvider(credsProvider);
	    context.setAuthCache(authCache);

	    HttpClient client = HttpClientBuilder.create().build();

	    String uri = "http://" + mqUrl.getHost() + ":" + mqUrl.getPort() + "/api/jolokia/read/org.apache.activemq:type=Broker,brokerName=localhost" + attr;

	    HttpResponse response = client.execute(new HttpGet(uri), context);
	    if (response.getStatusLine().getStatusCode() != 200) {
	        throw new IOException(response.getStatusLine().toString());
	    }
	    return IOUtils.toString(response.getEntity().getContent());
	}

}
